<template>
	<view class="container">
		<view class="header" v-if="!cart.recommend">
			<view class="header_nav">
				<view :class="cart.shopShow==1?'active':''" @tap="cart.changeShopShow(1)">全部({{brandCartList.length}})</view>
				<view v-if="brandSaleList.length" :class="cart.shopShow==2?'active':''" @tap="cart.changeShopShow(2)">即将开售({{brandSaleList.length}})</view>
				<view v-if="brandInvalidList.length" :class="cart.shopShow==3?'active':''" @tap="cart.changeShopShow(3)">已失效({{brandInvalidList.length}})</view>
			</view>
			<view class="isDetele" @click="cart.edit = !cart.edit">
				<image v-show="!cart.edit" class="edit_icon" :src="common.imageUrl('180')"></image>
				<view>{{ cart.edit ? "取消编辑" : "编辑" }}</view>
			</view>
		</view>
		<view class="main" v-if="!cart.recommend">
			<!-- 可购买商品 -->
			<view v-if="brandCartList.length&&cart.shopShow==1">
				<view class="shop_list" v-for="(v,i) in brandCartList" :key="v.id">
					<view class="list_title">
						<image class="radio"  @click="cart.choose('brand', v.radio, i)" :src="common.imageUrl(v.radio?'13':'12')"></image>
						<view><image :src="v.brandsLogo"></image><text class="brandsName">{{v.brandsName}}</text></view>
					</view>
					<productItem :introType='1' :list='v.shoppingCarVOlist' :indexs='i' @choose='cart.choose' @amount="cart.dealAmount" @changeSpecifications='specifications.changeSpecifications'></productItem>
				</view>
			</view>
			<!-- 即将开售商品 -->
			<view v-if="brandSaleList.length&&cart.shopShow!=3">
				<view class="shop_list brandSaleList">
					<view class="brandSaleList_title"><text>即将开售({{brandSaleList.length}})</text><text @tap="cart.deleteInvalidProduct(2)">删除</text></view>
					<productItem :introType='2' :list='brandSaleList' @changeSpecifications='specifications.changeSpecifications'></productItem>
				</view>
			</view>
			<!-- 失效商品 -->
			<view v-if="brandInvalidList.length&&cart.shopShow!=2">
				<view class="shop_list">
					<view class="brandSaleList_title brandInvalidList_title"><text>失效商品({{brandInvalidList.length}})</text><text @tap="cart.deleteInvalidProduct(1)">清空失效商品</text></view>
					<productItem :introType='3' :list='brandInvalidList' @changeSpecifications='specifications.changeSpecifications'></productItem>
				</view>
				
			</view>
		</view>
	    <!-- 结束 -->
	    <view class="cart-bottom" v-if="!cart.recommend">
	      <view class="select" @click="cart.choose('all')">
			  <image class="radio" :src="common.imageUrl(cart.all_radio?'13':'12')"></image>
			  <text @click="cart.choose('all')" class="font24">全选</text>
		  </view>
		  <view class="btnAndprice">
			  <view v-if="!cart.edit">总计: <text>¥{{cart.productMoney}}</text></view>
			  <view v-if="cart.edit" class="btn dele" @tap="cart.delectPro">删除</view>
			  <view v-else class="btn" @tap="cart.toSubmit">去结算</view>
		  </view>
	    </view>
		<view v-if="cart.recommend">
			<!-- 无数据推荐 -->
			<view class="noData">
				<image :src="common.imageUrl('54')" mode=""></image>
				<text>您的购物车是空的~</text>
				<view @tap="cart.toIndex">去逛逛</view>
			</view>
			<view class="recommend">
				<view class="recommend_title">为您推荐</view>
				<shopList :isLine="false" :list="recommend.list"></shopList>
			</view>
		</view>
		<!-- 商品身份购买弹框 -->
		<purchase ref="skuPopup" :cartMessage="specifications.cartMessage" :showPop="specifications.showPop" @selectShop="specifications.getSelectShop" @open="specifications.onOpenSkuPopup" />
	</view>
</template>
<script setup lang="ts">
import { reactive ,ref} from 'vue';
import api from "@/api";
import {onLoad,onShow} from '@dcloudio/uni-app'
import productItem from '@/pages/shopping/cart/components/product-item/product-item.vue'
import purchase from '@/pages/shopping/productDetails/components/purchase.vue'
import { useCartStoreToRefs,useCartStore } from "@/store/useCartStore";
const { addCart,getGartList,limitAmount,delectPro } = useCartStore()
const {brandOrderList,brandSaleList,brandInvalidList,brandCartList} = useCartStoreToRefs();
import { formatTime } from '@/hooks/useFunction'
onShow( async()=>{
	init()
})
const init = async() =>{
	uni.showLoading({
		mask: true,
		title: "加载中"
	})
	clearInterval(common.timer);
	await getGartList()
	cart.recommend = brandCartList.value.length || brandSaleList.value.length || brandInvalidList.value.length?false:true
	if(cart.recommend){
		recommend.getList()
	}else{
		await cart.getMoney()
	}
	await common.dealTime()
	uni.hideLoading()
}
const cart = reactive({
	edit:false,//判断当前状态  true 编辑  false 默认状态
	shopShow:1,//全部  2 即将开售  3  失效
	all_radio:false,//是否全部选中
	productMoney:'0',
	recommend:false,
	changeShopShow:(num:number)=>{//切换显示商品
		cart.shopShow = num
	},
	// 选中
	choose:async(type:string, status?:Boolean, i?:number, j?:number)=>{//选择商品
		  if (status == undefined) {
		    status = false;
		  }
		  switch (type) {
		    case "brand":
		       brandCartList.value[i].radio = !status;
		       brandCartList.value[i].shoppingCarVOlist.forEach((item) => {
		         item.radio = brandCartList.value[i].radio;
		       });
		       break;
		    case "single":
		       brandCartList.value[i].shoppingCarVOlist[j].radio = !status;
		       const statusChild = brandCartList.value[i].shoppingCarVOlist.find((item) => {
		           return item.radio == false || item.radio == undefined;
		       });
		       brandCartList.value[i].radio = statusChild ? false : true;
		       break;
		
		    case "all":
		       cart.all_radio = !cart.all_radio;
		       brandCartList.value.forEach((item) => {
		         item.radio = cart.all_radio;
		         item.shoppingCarVOlist.forEach((itemChild) => {
		           itemChild.radio = cart.all_radio;
		         });
		       });
		       break;
		  }
		  let data = {
		    addType: 2,
		    arr: brandCartList.value,
		    arrType: 2,
		    ifRadio: false,
		    isRequest: true,
		  };
		  await common.updataProduct(data);
		  await cart.getMoney()
	},
	//加减
	dealAmount : async (item:any, type:number) => {
	    switch (type) {
	        case 1:
	            item.amount--;
	            if (item.amount < 1) {
				    uni.showToast({
				   		icon: "none",
				   		title: "不能再减少了哦",
				   	});
	               item.amount = 1;
				   return
	            }
	            break;
	      case 2:
	           item.amount++;
	           if (item.amount >= 200) {
	             item.amount = 200;
	           }
	           let totalCount = item.amount || 0;
	           let limitNum = limitAmount(item, totalCount);
	           if (totalCount > limitNum) {
	             uni.showToast({
	               icon: "none",
	               title: "不能购买更多了哦",
	             });
	             item.amount = limitNum;
				return
	           }
	           break;
	    }
	    const params = {
	    	addType: 2,
	    	arr: [item],
	    	arrType: 1,
	    	ifRadio: false,
	    	isSelect: true,
	    };
	    await common.updataProduct(params);
		await cart.getMoney()
	    uni.hideLoading();
	},
	toSubmit:async()=>{
		let goodsList = brandCartList.value
		let choosePro = [];
		goodsList.forEach((item) => {
		  item.shoppingCarVOlist.forEach((itemChild) => {
		    if (itemChild.radio) {
		      choosePro.push(itemChild);
		    }
		  })
		})
		if (choosePro.length <= 0) {
		  uni.showToast({
		    icon: "none",
		    title: "请先勾选商品",
		  });
		  return;
		}
		brandOrderList.value = choosePro
		uni.navigateTo({
			url:'/pages/shopping/confirmOrder/index'
		})
	},
	//删除商品
	delectPro:()=>{
		let goodsList = brandCartList.value
		let choosePro = [];
		goodsList.forEach((item) => {
		  item.shoppingCarVOlist.forEach((itemChild) => {
		    if (itemChild.radio) {
		      choosePro.push(itemChild);
		    }
		  })
		})
		if (choosePro.length <= 0) {
		  uni.showToast({
		    icon: "none",
		    title: "请先勾选商品",
		  });
		  return;
		}
		uni.showModal({
		  title: `提示`,
		  content: `是否确定删除商品？`,
		  cancelText: "取消",
		  confirmText: "确定",
		  success: async (res) => {
			if (res.confirm) {
			  	const data = {
			  		addType: 4,
			  		arr: choosePro,
			  		arrType: 1,
			  		ifRadio: false,
			  		isRequest: true,
			  	};
			  	await common.updataProduct(data);
			  	await cart.getMoney()
			  	cart.edit = false;
			}
		  },
		});
	},
	//清除失效商品
	deleteInvalidProduct:async (type) => {
	  const data = {
	    addType: 4,
	    arr: type == 2 ? brandSaleList.value : brandInvalidList.value,
	    arrType: 1,
	    ifRadio: false,
	    isRequest: true,
	  };
	  if (type == 2) {
	    uni.showModal({
	      title: `提示`,
	      content: `是否确定删除商品？`,
	      cancelText: "取消",
	      confirmText: "确定",
	      success: async (res) => {
	         if(res.confirm){
				await common.updataProduct(data);
			 }
	      },
	    });
	    return false;
	  }
	  if (type == 1) {
	    await common.updataProduct(data);
	  }
	},
	getMoney: async()=> {
	  let allPrice = 0 //总价
	  brandCartList.value.forEach((item:any) => {
	    item.shoppingCarVOlist.forEach((itemChild) => {
	      if (itemChild.radio) {
	        allPrice += Number(itemChild.price) * Number(itemChild.amount);
	      }
	    });
	  })
	  cart.productMoney = allPrice.toFixed(2) || "0"; //实际支付价
	},
	toIndex:()=>{
		uni.switchTab({
			url:'/pages/onlineMall/index'
		})
	},
	
})
const skuPopup = ref(null)
//规格
const specifications = reactive<any>({
	cartMessage:{},
	showPop:false,
	//更换规格 打开弹框
	changeSpecifications:(item:any)=>{
		specifications.cartMessage = {
			...item,numberAdd:4,standard:6
		}
		specifications.showPop = true;
	},
	//选择规格组件返回数据
	getSelectShop:(e, status)=>{
		specifications.showPop = false;
		if (!status) {
			// common.updataProduct()
			init()
		}
	},
	//选择规格默认 sku组件 开始-
	onOpenSkuPopup:()=>{
		let properties = JSON.parse(specifications.cartMessage.skuProperties);
		let sku = [];
		
		properties.forEach(num => {
			sku.push(num.value)
		})
		skuPopup.value.details.selectSku({
			sku: sku,
			num:  specifications.cartMessage.amount
		});
	}
})
const recommend = reactive({
	list:[],
	getList: async()=>{
		const res:any = await api({
		  method: "get",
		  url: `/mall/goods/V2021/shoppingCar/goodsRecommend`,
		});
		recommend.list = res.data
	}
})
const common = reactive({
	// 响应式状态
	timer:null,
	color:'#FEDFE8',
	imageUrl: (id:string) => {
	  return `https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-${id}.png`;
	},
	dealTime: async()=>{
		if(brandSaleList.value.length==0){return}
		common.timer = setInterval(() => {
		    if(brandSaleList.value.some(e=>e.saleType && e.saleTime)){
				brandSaleList.value.forEach((item) => {
		  	 		if (item.saleType && item.saleTime) {
		  	 		    var result = formatTime().timeDifference(new Date(), item.saleTime);
		  	 		    item.timers = result;
		  	 		    if (!result) {
							item.saleType = 0;
		  	 		    }
		  	 		}
				});
		    }else{
				init()
			}
		}, 1000)
	},
	// 方法转换
	updataProduct : async (data:any = {}) => {
	  uni.showLoading({ title: "加载中" });
	  const {
	    addType,
	    arr,
	    arrType,
	    ifRadio,
	    brandId,
	    tag,
	  } = data;
	   const params = {addType,arr,arrType,ifRadio,isSelect: true,brandId,tag,};
	  	await addCart(params);
	    await getGartList(params);
	}
})
</script>
<style lang="scss" scoped>
.container{
	line-height: 1;
	background-color: #F9F6F6;
}
.header{
	width: 100%;
	padding: 32rpx 24rpx;
	box-sizing: border-box;
	background-color: #F9F6F6;
	position: static;top: 0;
	@include flex(center,space-between);
	.header_nav{
		@include flex(center);
		view{
			color: #7C807F;
			padding: 16rpx;
			font-size: 26rpx;
			background: #FFFFFF;
			margin-right: 16rpx;
			border-radius: 240rpx;
			&.active{
				color: #FF6084;
				background: #FEDFE8;
			}
		}
	}
	.isDetele{
		color: #1A1A1A;
		padding: 16rpx; 
		font-size: 26rpx;
		width: fit-content;
		background: #FFFFFF;
		border-radius: 240rpx;
		@include flex(center);
		image{
			width: 32rpx;
			height: 32rpx;
			margin-right: 4rpx;
		}
	}
}
::v-deep.uni-radio-input:hover {
  border-color: #999 !important;
}
.main{
	padding: 0 24rpx calc(var(--safe-area-bottom) + 136rpx);
	.brandSaleList_title{
		width: 100%;
		height: 72rpx;
		font-weight: bold;
		font-size: 26rpx;
		color: #FF6084;
		line-height: 72rpx;
		background: #FDE8EC;
		padding:0 32rpx;
		box-sizing: border-box;
		border-radius: 24rpx 24rpx 0 0;
		@include flex(center,space-between);
	}
	.brandInvalidList_title{
		color: #5C5E5E;
		background: #E4E6E6;		
	}
	.shop_list{
		width: 100%;
		margin-bottom: 24rpx;
		background: #FFFFFF;
		border-radius: 24rpx;
		.list_title{
			@include flex(center);
			box-sizing: border-box;
			padding: 40rpx 24rpx;
			font-weight: bold;
			font-size: 32rpx;
			color: #1B2120;
			view{
				@include flex(center);
				image{
					width: 64rpx;
					height: 64rpx;
					border-radius: 8rpx;
					margin-right: 8rpx;
				}
				.brandsName{
					width: 524rpx;				
				}
			}
		}
		.radio{
			width: 40rpx;
			height: 40rpx;
			margin-right: 24rpx;
		}	
	}
}
.cart-bottom{
	width: 100%;
	height: 136rpx;
	position: fixed;
	padding: 0 32rpx;
	box-sizing: border-box;
	background-color: #fff;
	left: 0;bottom: 0;z-index: 99;
	@include flex(center,space-between);
	padding-bottom: var(--safe-area-bottom);
	height: calc(var(--safe-area-bottom) + 136rpx);
	.select{
		@include flex(center);
		font-size: 30rpx;
		color: #1B2120;
		image{
			width: 48rpx;
			height: 48rpx;
			margin-right: 16rpx;
		}
	}
	.btnAndprice{
		@include flex(center);
		font-size: 24rpx;
		color: #1B2120;
		text{
			font-weight: bold;
			font-size: 32rpx;
			color: #FF6084;
		}
		.btn{
			width: 216rpx;
			height: 88rpx;
			color: #FFFFFF;
			font-size: 28rpx;
			margin-left: 16rpx;
			border-radius: 44rpx;
			@include flex(center,center);
			background: linear-gradient( 90deg, #FF6188 0%, #FF5252 100%);
		}
		.dele{
			// color: #FF6084;
			// background: #fff;
			// border:2rpx solid #FF6084;
		}
	}
}
.noData{
	width: 100%;
	font-size: 32rpx;
	color: #1B2120;
	background: #FFFFFF;
	border-radius: 24rpx;
	padding: 96rpx 0;
	@include flex(center,center);
	flex-direction: column;
	image{
		width: 350rpx;
		height: 284rpx;
	}
	text{
		margin: 40rpx 0 24rpx;
		text-align: center;
		font-size: 32rpx;
		color: #1B2120;
	}
	view{
		width: 260rpx;
		height: 88rpx;
		color: #ffffff;
		font-size: 28rpx;
		border-radius: 62rpx;
		@include flex(center,center);
		background: linear-gradient( 90deg, #FF6188 0%, #FF5252 100%);
	}
	
}
.recommend{
	padding: 0 32rpx;
	margin-top: 64rpx;
	box-sizing: border-box;
	.recommend_title{
		margin-bottom: 32rpx;
		font-weight: bold;
		font-size: 40rpx;
		color: #1B2120;
	}
}
</style>